淺談 Git Commit 規範
TLDR
- Angular Commit Format 結構為 Header (必填)、Body (選填) 與 Footer (選填)。
- Header 格式為
<type>(<scope>): <short summary>,其中type用於分類,summary應使用祈使句、不首字母大寫、結尾不加句點。 - 使用
git config --global commit.template <file_path>可設定全域 Commit 模板,提升撰寫規範的一致性。 - 設定
git config --global commit.cleanup strip可確保 Commit 時自動移除模板中的註解行與多餘空行。 - 透過
BREAKING CHANGE或DEPRECATED關鍵字可於 Footer 標註重大變更,並利用Closes #<issue_number>等語法自動關聯 Issue。
Commit Format 結構
Angular Commit Format 將訊息分為三個部分,各部分之間以空行隔開。
xml
<header>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>Header 規範
Header 是 Commit 訊息的核心,格式為 <type>(<scope>): <short summary>。
- Type:用於定義變更類型。
feat:新功能。fix:bug 修復。docs:僅限文件更新。refactor:既不修復錯誤也不增加功能的程式碼變更。test:補測試或更正現有測試。perf:提升效能的程式碼變更。build:影響打包機制或外部依賴關係的更改。ci:變更 CI 設定文件和腳本。
- Scope:表示受影響的模組或套件名稱,若無特定範圍可省略。
- Short Summary:簡潔描述變更內容。建議使用祈使句(如 "change" 而非 "changed")、不首字母大寫,且結尾不加句點。
Body 與 Footer
- Body:解釋變更的動機,並可對比修改前後的行為差異。若變更簡單則可省略。
- Footer:用於標註重大變更(
BREAKING CHANGE)、棄用資訊(DEPRECATED)或關聯 Issue。- 關聯 Issue 關鍵字:
close,closes,closed,fix,fixes,fixed,resolve,resolves,resolved。
- 關聯 Issue 關鍵字:
Commit Template 設定與應用
當開發者不熟悉規範或容易遺漏欄位時,可透過 Git Template 功能統一格式。
設定步驟
- 建立
.gitmessage.txt檔案,內容包含各欄位的說明與規範。 - 執行以下指令進行全域設定:git
git config --global commit.template ~/.gitmessage.txt git config --global commit.cleanup strip
參數說明
commit.template:指定 Commit 訊息的模板檔案位置。commit.cleanup strip:確保在執行 Commit 時,自動移除模板中的註解行(以#開頭的行)與多餘空行。
TIP
若 template 設定為 ./.gitmessage.txt,Git 會優先使用當前儲存庫根目錄下的檔案作為模板。
常見版控軟體支援狀況
什麼情況下會遇到註解無法自動移除的問題?當使用非命令列的 GUI Git 工具時,若該工具未正確處理 commit.cleanup 設定,可能導致註解行被誤認為 Commit 訊息的一部分。
- GitKraken:需在 Preferences 中手動勾選「Removes comments from commit messages」。
- Tortoisegit:預設不會忽略
#開頭的行。 - Git Extensions:會自動忽略
#開頭的行。 - Sourcetree:Windows 版 3.4.20 以上版本已支援 Git Template,並會自動忽略
#開頭的行。
異動歷程
- 2024-07-23 初版文件建立。
- 2024-09-20
- 更新 Windows 版 Sourcetree 3.4.20 支援 Git Commit Template 功能。
- 修正設定檔位置的說明。
